package org.chat.hhdchat.handler;

import com.alibaba.fastjson2.JSONObject;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.chat.hhdchat.entity.ChatMessage;
import org.chat.hhdchat.repository.ChatMessageRepository;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

// 消息处理逻辑
@Component
@ChannelHandler.Sharable
public class ChatServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    // 存储在线用户的Channel（Key: 用户ID）
    private static final Map<String, Channel> onlineUsers = new ConcurrentHashMap<>();
    private final ChatMessageRepository chatMessageRepository;

    public ChatServerHandler(ChatMessageRepository chatMessageRepository) {
        this.chatMessageRepository = chatMessageRepository;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
        // 解析JSON消息
        JSONObject json = JSONObject.parse(msg.text());
        String type = json.getString("type");
        System.out.println("消息：" + json + "类型 :" + type);

        switch (type) {
            case "LOGIN":
                handleLogin(ctx, json);
                break;
            case "SINGLE_MSG":
                handleSingleMessage(json);
                break;
            case "PULL_OFFLINE_MSG":
                handlePullOfflineMsg(json);
                break;
        }
    }

    // 处理用户登录
    private void handleLogin(ChannelHandlerContext ctx, JSONObject json) {
        String userId = json.getString("userId");
        onlineUsers.put(userId, ctx.channel());
        System.out.println("用户 " + userId + " 上线了");
    }

    // 处理单聊消息
    private void handleSingleMessage(JSONObject json) {
        System.out.println("单聊逻辑");
        String from = json.getString("from");
        String to = json.getString("to");
        String content = json.getString("content");

        // 1. 存储到数据库（无论对方是否在线）
        ChatMessage message = new ChatMessage();
        message.setFromUserId(from);
        message.setToUserId(to);
        message.setContent(content);
        System.out.println("from user id:" + message.getFromUserId());
        chatMessageRepository.save(message);
        System.out.println("MongoDB存储成功");

        // 2. 如果对方在线，直接转发
        Channel targetChannel = onlineUsers.get(to);
        if (targetChannel != null && targetChannel.isActive()) {
            targetChannel.writeAndFlush(new TextWebSocketFrame(json.toString()));
            message.setRead(true); // 标记为已读
            chatMessageRepository.save(message);
        }
    }

    // 处理拉取离线消息
    private void handlePullOfflineMsg(JSONObject json) {
        String userId = json.getString("userId");
        List<ChatMessage> offlineMessages = chatMessageRepository.findByToUserIdAndIsReadFalse(userId);
        System.out.println("离线的数据:"+offlineMessages);
        Channel channel = onlineUsers.get(userId);

        if (channel != null) {
            offlineMessages.forEach(msg -> {
                JSONObject response = new JSONObject();
                response.put("type", "OFFLINE_MSG");
                response.put("from", msg.getFromUserId());
                response.put("content", msg.getContent());
                channel.writeAndFlush(new TextWebSocketFrame(response.toString()));
                msg.setRead(true); // 标记为已读
                chatMessageRepository.save(msg);
            });
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        // 用户断开连接时，移除在线状态
        System.out.println("离线");
        onlineUsers.values().removeIf(channel -> channel == ctx.channel());
    }
}